package com.cisdi.my.shop.web.controller;

import com.cisdi.my.shop.commons.context.SpringContext;
import com.cisdi.my.shop.commons.utils.CookieUtils;
import com.cisdi.my.shop.entity.User;
import com.cisdi.my.shop.service.UserService;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author pengyangyan
 * @version 1.0.0
 * @date 2019年09月16日 13:57:00
 */
public class LoginController extends HttpServlet {

    private static final String COOKIE_NAME_USER_INFO = "userInfo";


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userInfo = CookieUtils.getCookieValue(req, COOKIE_NAME_USER_INFO);
        if (StringUtils.isNotBlank(userInfo)){
            String[] userInfoArr = userInfo.split(":");
            String email = userInfoArr[0];
            String password = userInfoArr[1];
            req.setAttribute("email",email);
            req.setAttribute("password",password);
            req.setAttribute("isRemember",true);
        }
        req.getRequestDispatcher("/login.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        Boolean isRemember = req.getParameter("isRemember") != null ? true : false;
        SpringContext springContext = new SpringContext();
        UserService userService = (UserService) springContext.getBean("userService");
        User user = userService.login(email, password);

        if (user != null){
            if (isRemember){
                CookieUtils.setCookie(req,resp,COOKIE_NAME_USER_INFO,String.format("%s:%s",email,password),7*24*60*60);
            }else {
                CookieUtils.deleteCookie(req,resp,COOKIE_NAME_USER_INFO);
            }
            resp.sendRedirect("/main.jsp");
        }else {
            req.setAttribute("message","用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}
